﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using XfTechOAWeb.ApiServer.Auth;
using XfTechOAWeb.Dtos;
using XfTechOAWeb.Dtos.Roles;
using XfTechOAWeb.Infrastructure.RedisCache;

namespace XfTechOAWeb.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        private readonly IRoleService _roleService;
        public RoleController(IRoleService roleService)
        {
            _roleService = roleService;
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]//请求方式
        public IActionResult Post(RoleAddDto role)
        {
            //模型验证：把用户通过网络，HTTP协议提交的数据，与action方法的模型绑定的过程
           //1.验证
            if(!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = role });
            }

            int result = _roleService.Add(role);
            if(result == 0)
            {
                return Ok(new ResponseModel<object> { Code = 302, Msg = "参数有误", Data = role });
            }
            return Ok(new ResponseModel<object> { Code = 200, Msg = "添加成功", Data = role });
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Put(Role role)
        {

            if(!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = role });
            }

            int result = _roleService.Upt(role);
            if(result == 0)
            {
                return Ok(new ResponseModel<object> { Code = 302, Msg = "参数有误", Data = role });
            }
            return Ok(new ResponseModel<object> { Code = 200, Msg = "修改成功", Data = role });
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult Delete(RoleDeleteDTO role)
        {

            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = role.ids });
            }

            int result = _roleService.Del(role.ids);
            if (result == 0)
            {
                return Ok(new ResponseModel<object> { Code = 302, Msg = "参数有误", Data = role.ids });
            }
            return Ok(new ResponseModel<object> { Code = 200, Msg = "修改成功", Data = role.ids });
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="findPage"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get([FromQuery]RoleFindPageDto findPage) 
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误" });
            }
            return Ok(new { msg = true, data = _roleService.Show(findPage) });
        }
        /// <summary>
        /// 给角色添加权限
        /// </summary>
        /// <param name="rolePermission"></param>
        /// <returns></returns>
        [HttpPost("addPermission")]
        public IActionResult Post(RoleAddPermissionDto rolePermission, [FromServices]ICSRedisHelper redisClient)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = rolePermission });
            }

            int result = _roleService.AddRolePermission(rolePermission.RId, rolePermission.PId);
            if (result == 0)
            {
                return Ok(new ResponseModel<object> { Code = 302, Msg = "参数有误", Data = rolePermission });
            }

            //如果添加成功，则需要找到分配了该角色的所有用户ID，并清空redis缓存
            _roleService.GetRoleUser(rolePermission.RId).ForEach(uId =>
            {
                //这里的key是角色的id
                var key = $"userId_{uId}_menu";
                redisClient.Del(key); //删除键值
            });

            return Ok(new ResponseModel<object> { Code = 200, Msg = "添加成功", Data = rolePermission }); 
        }

        /// <summary>
        /// 获取角色拥有的权限 
        /// </summary> ygg
        /// <param name="rid"></param>
        /// <returns></returns>
        //[HttpGet("{rid}")]
        //public IActionResult GetPer(int rid) 
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = rid });
        //    }
        //    int result = Convert.ToInt32(_roleService.PTree(rid));
        //    if (result == 0)
        //    {
        //        return Ok(new ResponseModel<object> { Code = 302, Msg = "参数有误", Data = rid });
        //    }
        //    return Ok(new ResponseModel<object> { Code = 200, Msg = "添加成功", Data = rid });
        //}

        [HttpGet("{rid}")]
        public IActionResult GetPer(int rid)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = rid });
            }
            
            else
            {
                return Ok(new ResponseModel<object> { Code = 200, Msg = "获取成功", Data = _roleService.GetRolePermission(rid) });
            };        
        }
        /// <summary>
        /// 角色名唯一验证
        /// </summary>
        /// <param name="RName"></param>
        /// <returns></returns>
        [HttpGet("UniqueRName/{RName}")]
        public IActionResult UniqueRName(string RName)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object> { Code = 301, Msg = "参数有误", Data = RName });
            }

            else
            {
                return Ok(new ResponseModel<object> { Code = 200, Msg = "获取成功", Data = _roleService.UniqueRName(RName) });
            };
        }
    }
}
